package com.xma.springcloud.alibaba.service.impl;

import com.xma.springcloud.alibaba.dao.TtOrderDao;
import com.xma.springcloud.alibaba.entity.TtOrder;
import com.xma.springcloud.alibaba.service.TtAccountService;
import com.xma.springcloud.alibaba.service.TtOrderService;
import com.xma.springcloud.alibaba.service.TtStorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * (TtOrder)表服务实现类
 *
 * @author makejava
 * @since 2020-07-06 19:53:14
 */
@Service("ttOrderService")
@Slf4j
public class TtOrderServiceImpl implements TtOrderService {
    @Resource
    private TtOrderDao ttOrderDao;

    @Resource
    private TtStorageService ttStorageService;

    @Resource
    private TtAccountService ttAccountService;

    /**
     * 通过ID查询单条数据
     *
     * @param
     * @return 实例对象
     */
    @Override
    public TtOrder queryById(Long id ) {
        return this.ttOrderDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<TtOrder> queryAllByLimit(int offset, int limit) {
        return this.ttOrderDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param ttOrder 实例对象
     * @return 实例对象
     */

    @GlobalTransactional(name = "create-order",timeoutMills = 300000,rollbackFor ={Throwable.class,Exception.class})
    @Override
    //@Transactional
    public TtOrder insert(TtOrder ttOrder) {

        //1 新建订单
        log.info("--------开始新建订单");
        this.ttOrderDao.insert(ttOrder);
        //2 扣减库存7
        log.info("--------订单微服务开始调用库存，做扣减");
        ttStorageService.decrease(ttOrder.getProductId(),ttOrder.getCount());
        log.info("--------订单微服务开始调用库存，做扣减end");
        //  3 扣减账户
        log.info("------订单微服务开始调用账户，做扣减");
        //BigDecimal money = BigDecimal.valueOf(ttOrder.getCount() * ttOrder.getMoney().doubleValue()) ;
        ttAccountService.decrease(ttOrder.getUserId(),ttOrder.getMoney());
        log.info("------订单微服务开始调用账户，做扣减end");

        //4 修改订单状态，从零到1，1 代表已经完成
        log.info("-------修改订单状态开始");
        ttOrder.setStatus(0);
        this.ttOrderDao.update(ttOrder);
        log.info("-------修改订单状态结束");
        log.info("-------下订单结束了，哈哈哈哈哈。。。。。");
        return ttOrder;
    }

    /**
     * 修改数据
     *
     * @param ttOrder 实例对象
     * @return 实例对象
     */
    @Override
    public TtOrder update(TtOrder ttOrder) {
        this.ttOrderDao.update(ttOrder);
        return this.queryById(ttOrder.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param
     * @return 是否成功
     */
    @Override
    public boolean deleteById( Long id) {
        return this.ttOrderDao.deleteById(id) > 0;
    }
}